/*
 * @(#)ShopInitController.java 2012-01-11
 *
 * Copyright 2011 北龙中网（北京）科技有限责任公司. All rights reserved.
 */
package cn.shangjia.shop.controller.base;

import java.util.Collection;
import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;

import cn.shangjia.common.domain.CompanyInfo;
import cn.shangjia.common.domain.NewsOnline;
import cn.shangjia.common.domain.Shop;
import cn.shangjia.common.domain.ShopDir;
import cn.shangjia.common.domain.ShopStatCode;
import cn.shangjia.common.domain.User;
import cn.shangjia.common.domain.UserContactOnline;
import cn.shangjia.common.domain.UserInfo;
import cn.shangjia.common.domain.support.PostType;
import cn.shangjia.common.domain.support.State;
import cn.shangjia.common.domain.support.UserType;
import cn.shangjia.common.util.StringUtils;
import cn.shangjia.common.web.session.KnetSession;
import cn.shangjia.shop.config.Constants;
import cn.shangjia.shop.domain.type.TemplateType;
import cn.shangjia.shop.exception.NotFoundException;
import cn.shangjia.shop.exception.UserLockedException;
import cn.shangjia.shop.service.CompanyImgService;
import cn.shangjia.shop.service.CompanyInfoService;
import cn.shangjia.shop.service.MessageService;
import cn.shangjia.shop.service.NewsService;
import cn.shangjia.shop.service.ShopInfoService;
import cn.shangjia.shop.service.impl.common.CommonService;

/**
 * 初始化商铺
 *
 * @author <a href="mailto:jinzhongze@knet.cn">jinzhongze</a>
 * @version 1.0, 2012-01-11 11:42:59
 * @since 1.0
 */
public abstract class ShopInitController extends AbstractController {
	
	@Resource
	protected ShopInfoService shopInfoService;
	
	@Resource
	protected CompanyInfoService companyInfoService;
	
	@Resource
	protected CompanyImgService companyImgService;
	
	@Resource
	protected NewsService newsService;
	
	@Resource
	protected MessageService messageService;
	
	@Resource
	protected CommonService  commonService;
	
	/**
	 *  初始化商铺
	 * 
	 * @param username
	 * @param map
	 * @return
	 * @author <a href="mailto:jinzhongze@knet.cn">jinzhongze</a>
	 */
	@ModelAttribute(Constants.USER)
	public User initShop(@PathVariable("username")  String username,  ModelMap map) {

		User user = userInfoService.getUser(username);
		if (user == null) { //  如果 ID 不存在
			throw new NotFoundException();
		}
		if (!State.ACTIVATED.equals(user.getState())) { //用户不是正常激活状态 //TODO 这些操作都有待处理
			throw new UserLockedException(username);
		}
		String userId = user.getId();
		
		//加载企业信息
		CompanyInfo companyInfo = companyInfoService.getCompanyInfoByUserId(userId);
		map.addAttribute(Constants.COMPANY_INFO, companyInfo);
		
		//加载商铺信息
		Shop shop = shopInfoService.getShopByUserId(userId);
		map.addAttribute(Constants.SHOP, shop);
		
		//供求目录 小模块 //4条
		//加载 供应 分类  
		Collection<ShopDir> supply = shopInfoService.findShopDirList(userId,PostType.PRODUCT,4);
		map.addAttribute(Constants.MOD_DIR_SUPPLY, supply);
		
		//加载 求购 分类 //4条
		Collection<ShopDir> buy = shopInfoService.findShopDirList(userId,PostType.BUY,4);
		map.addAttribute(Constants.MOD_DIR_BUY, buy);
		
		//加载 小模块 企业动态  //6条
		Collection<NewsOnline> news = newsService.findNewsPage(userId, 1, 6).getResult();
		map.addAttribute(Constants.MOD_NEWS, news);
		
		//加载 模板  
		map.addAttribute(Constants.TEMPLATE, getSkin(shop));
		
		//加载 用户联系人信息
		UserContactOnline userContact = userInfoService.getUserContactOnline(userId);
		map.addAttribute(Constants.USER_CONTACT, userContact);
		
		//加载 统计代码
		ShopStatCode ssc = shopInfoService.getShopStatCodeByUserId(userId);
		if (ssc != null ) {
			String statCode = ssc.getStatCode();
			if (!StringUtils.isEmpty(statCode)) {
				ssc.setStatCode(statCode.replaceAll("&lt;", "<")
						.replaceAll("&gt;", ">").replaceAll("&amp;", "&"));
			}
		}
		map.addAttribute(Constants.SHOP_STAT_CODE, ssc);
		
		//判定该用户是否 是vip用户
		map.addAttribute("isVip", UserType.VIP.equals(user.getUserType()));
		
		//将最常用的 userid 和 username 加载到页面
		map.addAttribute("userid", userId);
		map.addAttribute("username", user.getUsername());
		
		return user;
	}
	
	/**
	 *  验证登陆. 并设置到request对象
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @author <a href="mailto:jinzhongze@knet.cn">jinzhongze</a>
	 */
	@ModelAttribute(Constants.CURRENT_USERINFO) 
	public UserInfo setCurrentUserInfo(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		//单点登录 - 验证用户是否登陆 . 如果是 将用户 信息放到request
		UserInfo userInfo = getCurrentUser(request, response);
		
		if (userInfo != null) {
			 String skin = getViewSkin(userInfo.getUser().getId(), /*这里的userId是商铺所有者id*/(String)model.get("userid"), request, response);
			 if (skin != null) {
				 model.addAttribute(Constants.TEMPLATE, skin);
			 }
		} 
		
		return userInfo;
	}
	
	
	/**
	 *  设置环境路径
	 * 
	 * @param request
	 * @return
	 * @author <a href="mailto:jinzhongze@knet.cn">jinzhongze</a>
	 */
	@ModelAttribute("contextpath")
	public String setContextPath(HttpServletRequest request) {
		return request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
	}
	
	/**
	 *  设置当天页面访问路径
	 * 
	 * @param request
	 * @return
	 * @author <a href="mailto:jinzhongze@knet.cn">jinzhongze</a>
	 */
	@ModelAttribute("currenturl")
	public String setCurrentUrl(HttpServletRequest request) {
		StringBuffer sb = request.getRequestURL();
		if (sb == null)
			return null;
		String queryString = request.getQueryString();
		if(!StringUtils.isEmpty(queryString))
			sb.append("?").append(queryString);
		return sb.toString();
	}
	
	/**
	 *  获取模板
	 * 
	 * @param shop
	 * @return
	 * @author <a href="mailto:jinzhongze@knet.cn">jinzhongze</a>
	 */
	private String getSkin(Shop shop) {
		String defaultValue = TemplateType.C.getValue();
		if (shop == null)
			return defaultValue;
		String template = shop.getTemplate();
		if (StringUtils.isEmpty(template)) 
			return defaultValue;
		if (!TemplateType.valueList().contains(template))
			return defaultValue;
		return template;
	}
	
	
	/**
	 *  如果是预览的模板
	 * 
	 * @param userId
	 * @param shopId
	 * @param request
	 * @param response
	 * @return
	 * @author <a href="mailto:jinzhongze@knet.cn">jinzhongze</a>
	 */
	private String getViewSkin(String userId, String shopId, HttpServletRequest request, HttpServletResponse response) {
		
		if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(shopId)) //如果没有登录. 
			return null; 
		if (!StringUtils.equals(userId, shopId)) //如果该登录用户访问的不是自己的商铺
			return null; 
		
		final String key = cn.shangjia.common.Constants.SHOP_VIEW_KEY + "-" + userId; 
		
		KnetSession session = getSession(request, response);
		Map<String, Object> map = session.get(key);
		
		if (map == null) { //如果 此人没有点预览 , session没有他的预览数据
			return null;
		}
		
		try { //如果 session中有预览信息 . 先判断 是否 超时, 超时清空干掉预览信息
			Date time = (Date) map.get("time");
			if (time == null || (new Date().getTime() - time.getTime()) > 60000 /*默认给保存1分钟*/) {
				session.remove(key);  //超时清掉该session 恢复正常访	问.
				return null;
			}
		} catch(Exception e) {
			return null;
		}
		
		//如果 到此 . 说明 用户 是在预览自己的商铺. 返回session中的模板信息
		String skin = (String) map.get("skin");
		Shop shop = new Shop();
		shop.setTemplate(skin);
		return getSkin(shop);
		
	}
	
}
